package com.mytools;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import com.mytools.util.ImgMatchUtil;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.jsoup.internal.StringUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PinterestClient {


    public static void main(String[] args) throws Exception{
        final JFrame jf = new JFrame("工具窗口");
        jf.setSize(700, 500);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.setLayout(new GridLayout(5,1));

        Panel a=new Panel();//定义上半部分
        JLabel ipLabel = new JLabel("代理ip");
        ipLabel.setFont(new Font(null, Font.PLAIN, 15));
        JLabel portLabel = new JLabel("代理端口");
        portLabel.setFont(new Font(null, Font.PLAIN, 15));
        JTextField  ipField= new JTextField("", 15);
        JTextField  portField= new JTextField("", 5);
        a.add(ipLabel);
        a.add(ipField);
        a.add(portLabel);
        a.add(portField);
        jf.add(a);
        Panel b=new Panel();//定义上半部分
        jf.add(b);
        JLabel cookie = new JLabel("cookie");
        cookie.setFont(new Font(null, Font.PLAIN, 15));
        b.add(cookie);
        JTextField  cookieField= new JTextField("", 30);
        b.add(cookieField);
        Panel c=new Panel();//定义上半部分
        jf.add(c);
        JLabel data = new JLabel("搜索内容");
        data.setFont(new Font(null, Font.PLAIN, 15));
        c.add(data);
        JTextField  dataField= new JTextField("", 10);
        c.add(dataField);

        final JTextField pathField = new JTextField("D:\\File", 10);
        pathField.setFont(new Font(null, Font.PLAIN, 15));
        c.add(pathField);
        JButton btn2 = new JButton("选择excel存储路径");
        btn2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showFileSaveDialog(jf, pathField);
            }
        });
        c.add(btn2);

        Panel d=new Panel();//定义上半部分
        jf.add(d);
        JButton downloadButton=new JButton("下载");
        d.add(downloadButton);

        Panel e=new Panel();//定义上半部分
        JLabel tips = new JLabel("这是个提示");
        e.add(tips);
        jf.add(e);


        jf.setVisible(true);
        downloadButton.addActionListener(new ActionListener() {
            @Override
            public synchronized void actionPerformed(ActionEvent e) {
                String proxyHost = ipField.getText();
                String proxyPort = portField.getText();
                if(isNotEmpty(proxyHost)&&isNotEmpty(proxyPort)){
                    System.setProperty("https.proxyHost", proxyHost);
                    System.setProperty("https.proxyPort", proxyPort);
                }
                String cookie=cookieField.getText();
                if(isEmpty(cookie)){
                    JOptionPane.showMessageDialog(jf, "请先输入cookie", "错误", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                String data=dataField.getText();
                if(isEmpty(data)){
                    JOptionPane.showMessageDialog(jf, "输入搜索内容", "错误", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                List<List<?>> rows =new ArrayList<>();
                List<String> headRow = CollUtil.newArrayList("id", "url", "image", "grid_title", "link", "display_description");
                rows.add(headRow);

                String book="";
                for(int i=0;i<10;i++){
                    try {
                        tips.setText(i+"");
                        book=doReq(rows,cookie,book,data);
                        Thread.sleep(2000);
                        if(book==null || "".equals(book)){
                            break;
                        }
                    }catch(Exception e1){
                        e1.printStackTrace();
                    }
                }
                WriteCsvFile(pathField.getText(), rows);
                JOptionPane.showMessageDialog(jf, "下载完成", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        });
    }

    public static String doReq(List<java.util.List<?>> rows, String cookie,String book,String key){
        String data="{\"options\":{\"article\":null,\"appliedProductFilters\":\"---\",\"auto_correction_disabled\":false,\"corpus\":null,\"customized_rerank_type\":null,\"filters\":null,\"query\":\"fabric sofa\",\"query_pin_sigs\":null,\"redux_normalize_feed\":true,\"rs\":\"ac\",\"scope\":\"pins\",\"source_id\":null,\"no_fetch_context_on_resource\":false},\"context\":{}}";
        if(!StringUtil.isBlank(book)){
            data="{\"options\":{\"article\":null,"+"\"bookmarks\":[\""+book+"\"],"+"\"appliedProductFilters\":\"---\",\"auto_correction_disabled\":false,\"corpus\":null,\"customized_rerank_type\":null,\"filters\":null,\"query\":\""+key+"\",\"query_pin_sigs\":null,\"redux_normalize_feed\":true,\"rs\":\"ac\",\"scope\":\"pins\",\"source_id\":null,\"no_fetch_context_on_resource\":false},\"context\":{}}";
        }
        HttpRequest req= HttpUtil.createPost("https://www.pinterest.com/resource/BaseSearchResource/get");
        req.header("cookie",cookie);
        String csrftoken= ImgMatchUtil.getMatchList(cookie, "csrftoken=.*; ", true).get(0);
//        System.out.println(csrftoken.substring(10,42));
        req.header("x-csrftoken",csrftoken.substring(10,42));
//        req.form("source_url","/search/pins/?rs=ac&len=2&q=fabric%20sofa&eq=fabric%20sofa&etslf=2106&term_meta[]=fabric%7Cautocomplete%7C0&term_meta[]=sofa%7Cautocomplete%7C0");
        req.form("data",data);

        String s=req.execute().body();
        if(JSONUtil.isTypeJSONObject(s)){
            JSONObject obj=JSONUtil.parseObj(s);
            Object s1= obj.getByPath("resource_response.data.results");
            if(s1==null){
                return null;
            }
            List<JSONObject> beans=(List)s1;
            for(JSONObject bean:beans){
                if(!"pin".equals(bean.get("type"))){
                    continue;
                }

                List<?> row = CollUtil.newArrayList(bean.get("id"), "https://www.pinterest.com/pin/"+bean.get("id")+"/",
                        bean.getByPath("images.orig.url"), bean.get("grid_title"),
                        bean.getByPath("link"), bean.getByPath("rich_summary.display_description"));
                rows.add(row);
            }
            return obj.getByPath("resource_response.bookmark")+"";
        }
        return null;
    }

    public static void WriteCsvFile(String path, List<List<?>> rows) {
        try {
            String fileName =path +"\\"+ new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".xlsx";
            BigExcelWriter writer = ExcelUtil.getBigWriter(fileName);
            //设置内容字体
            org.apache.poi.ss.usermodel.Font font = writer.createFont();
            font.setColor(org.apache.poi.ss.usermodel.Font.COLOR_NORMAL);

            //默认单元格样式
            CellStyle defauleStyle = writer.getCellStyle();
            defauleStyle.setFont(font);
            CellStyle numberStyle = writer.getStyleSet().getCellStyle();
            StyleUtil.setAlign(numberStyle, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
            // 一次性写出内容，使用默认样式
            rows.forEach(k -> {
                writer.writeRow(k);
            });
            // 关闭writer，释放内存
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static String showFileSaveDialog(Component parent, JTextField msgTextArea) {
        // 创建一个默认的文件选取器
        JFileChooser fileChooser = new JFileChooser();

        // 设置打开文件选择框后默认输入的文件名
//        fileChooser.setSelectedFile(new File("测试文件.zip"));

        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        // 打开文件选择框（线程将被阻塞, 直到选择框被关闭）
        int result = fileChooser.showSaveDialog(parent);

        if (result == JFileChooser.APPROVE_OPTION) {
            // 如果点击了"保存", 则获取选择的保存路径
            File file = fileChooser.getSelectedFile();
            msgTextArea.setText(file.getAbsolutePath());
            return file.getAbsolutePath();
        }
        return "";
    }
    static boolean isEmpty(String str){
        return  str==null || "".equals(str);
    }
    static boolean isNotEmpty(String str){
        return  !(str==null || "".equals(str));
    }

}
